<?php
// public/audit_logs.php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();

$title = "Audit Logs | JO & COS RMS";

// Fetch logs
$stmt = $pdo->query("SELECT a.*, u.name as user_name 
                     FROM audit_logs a 
                     JOIN users u ON a.user_id = u.id
                     ORDER BY a.created_at DESC");
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle report export
if (isset($_GET['export'])) {
    $type = $_GET['export'];

    if ($type === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="audit_logs.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['User', 'Action', 'Details', 'Date']);
        foreach ($logs as $log) {
            fputcsv($out, [$log['user_name'], $log['action'], $log['details'], $log['created_at']]);
        }
        fclose($out);
        exit;
    }

    if ($type === 'excel') {
        require_once __DIR__ . '/../vendor/autoload.php';
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->fromArray(['User', 'Action', 'Details', 'Date'], NULL, 'A1');
        $row = 2;
        foreach ($logs as $log) {
            $sheet->fromArray(
                [$log['user_name'], $log['action'], $log['details'], $log['created_at']],
                NULL,
                "A{$row}"
            );
            $row++;
        }
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="audit_logs.xlsx"');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }

    if ($type === 'pdf') {
        require_once __DIR__ . '/../vendor/autoload.php';
        $pdf = new \TCPDF();
        $pdf->AddPage();
        $html = "<h2>Audit Logs Report</h2>
                 <table border='1' cellpadding='4'>
                    <tr><th>User</th><th>Action</th><th>Details</th><th>Date</th></tr>";
        foreach ($logs as $log) {
            $html .= "<tr>
                        <td>".htmlspecialchars($log['user_name'])."</td>
                        <td>".htmlspecialchars($log['action'])."</td>
                        <td>".htmlspecialchars($log['details'])."</td>
                        <td>{$log['created_at']}</td>
                      </tr>";
        }
        $html .= "</table>";
        $pdf->writeHTML($html);
        $pdf->Output('audit_logs.pdf', 'D');
        exit;
    }
}

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<section class="content-header">
  <div class="container-fluid d-flex justify-content-between align-items-center">
    <h1>Audit Logs</h1>
    <div>
      <a href="?export=csv" class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-csv"></i> CSV</a>
      <a href="?export=excel" class="btn btn-sm btn-outline-success"><i class="fas fa-file-excel"></i> Excel</a>
      <a href="?export=pdf" class="btn btn-sm btn-outline-danger"><i class="fas fa-file-pdf"></i> PDF</a>
    </div>
  </div>
</section>

<section class="content">
  <div class="card">
    <div class="card-body">
      <table id="logsTable" class="table table-bordered table-striped">
        <thead>
          <tr>
            <th>User</th>
            <th>Action</th>
            <th>Details</th>
            <th>Date</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($logs as $log): ?>
          <tr>
            <td><?= htmlspecialchars($log['user_name']) ?></td>
            <td><?= htmlspecialchars($log['action']) ?></td>
            <td><?= htmlspecialchars($log['details']) ?></td>
            <td><?= $log['created_at'] ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</section>

<?php include __DIR__ . '/../includes/footer.php'; ?>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css"/>

<script>
$(function () {
  $('#logsTable').DataTable({
    "responsive": true,
    "autoWidth": false
  });
});
</script>
